<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<script>
$(document).ready(function(){
	google.maps.visualRefresh = true;
	mainCss();
	$(document).on("click",function(e){
		if(!choicePosition){
			emptyChoice(false);	
		}
	});
	$("input.address.map").keyup(check);
	$("input.address.map").attr('placeholder', "현재 위치는 마커로 움직이거나, 주소를 이곳에 입력하여 조절할 수 있습니다.");
	$("input.address.move").css({
		"position":"absolute",
		"top":$("input.address.map").position().top + 3,
		"right" : 5,
		"font-size":"14pt",
		"padding":"5px"
	});
	$("#wait_time").css({
		"display":"none"
	});
	$("#response").css({
		"display":"none",
		"font-size":"16pt",
		"margin-top":"15px"
	});
	$("#accept").css({
		"display":"inline-block",
		"margin-right":"20px",
		"padding":"5px 15px ",
		"background-color":"green"
	});
	$("#reject").css({
		"display":"inline-block",
		"padding":"5px 15px ",
		"background-color":"red"
	});
	$("#waitInstruction").css({
		"font-family":"myFont",
		"font-size":"24pt",
	});
	$("#requestAddress").css({
		"margin":"10px 0"
	});
	$("#startWaiting").click(function(){
		$("input.address.map").css({
			"display":"none"
		});
		$("input.address.move").css({
			"display":"none"
		});
		$("#waitInstruction").css({
			"display":"none"
		});
		$("#wait_time").css({
			"display":"block",
		});
		$("#startWaiting").css({
			"display":"none"
		});
		setTimeout(function(){},1000*60*penalty);
		startWatch();
		$.getJSON("/kosta_project_final_taxi/driverRequestWaitCustomer.do","longitude="+driverPosition.lng()+"&latitude="+driverPosition.lat(), function(data){
			currentPosition = data.currentPosition; 
			waitResponse();
		});
	});
	
	$("#accept").click(function(){
		penalty = 0;
		var position = driverPosition.lat()+','+driverPosition.lng(); 
		$.getJSON("/kosta_project_final_taxi/acceptCustomerRequest.do","currentPosition="+position, function(){});
		$("#response").css({
			"display":"none"
		});
	});
	
	$("#reject").click(function(){
		penalty = (penalty * 2) + 3;
		$.getJSON("/kosta_project_final_taxi/rejectCustomerRequest.do","currentPosition="+currentPosition, function(){});
		responseFunction();
	});
	makeButton($("#startWaiting"));
	makeButton($("#accept"));
	makeButton($("#reject"));
	if (navigator.geolocation){
		navigator.geolocation.getCurrentPosition(driverPositionMap);
	}else{
		x.innerHTML="Geolocation is not supported by this browser.";
	}
});

function mainCss(){
	$("div.main").css({
		"width":"inherit",
		"height":$("div.container").height(),
		"font-family":"myFont",
		"font-size":"24pt"
	});
	$("input.address.map").css({
		"width":$("div.main").width(),
		"text-align":"center",
		"font-family":"myFont",
		"padding":"10px 0 10px 0",
		"font-size":"12pt"
	});
	$("#startWaiting").css({
		"vertical-align" : "middle",
		"height":160.5 / 3,
		"width":159 / 3,
	});
	$("#map_canvas").css({
		"width":$("div.main").width(),
		"height":$("div.main").height() * 7.5 / 10
	});
	$("div.address.choice").on("mouseover","div.address.option",function(){
		$("div.address.option").css({
			"background-color":"white",
		});
		$(this).css({
			"background-color":"#E6E6E6",
		});
		currNum = options.indexOf($(this).text());
		$("input.address.map").val($(this).text());
	});
	$("div.address.choice").on("mouseover",function(){
		choicePosition = true;
	});
	$("div.address.choice").on("mouseout",function(){
		choicePosition = false;
	});
	$("div.address.choice").on("mouseout","div.address.option",function(){
		$(this).css({
			"background-color":"white",
		});
		currNum = 0;
		$("input.address.map").val(options[0]);
	});
	$("div.address.choice").on("click","div.address.option",function(){
		$("input.address.map").val($(this).text().trim());
		if(addressUnitLevel<3){
			emptyChoice(false);
		}
		check({keyCode:32});
		currNum = 0;
		$("input.address.map").focus();
	});
	$("div.address.choice").css({
		"display":"none",
		"position":"absolute",
		"background-color":"white",
		"opacity":"0.9",
		"box-shadow": "0px 2px 2px 2px #888888",
		"padding":"10px 0px 15px 0px",
		"z-index":"3",
		"top":$("input.address.map").position().top+40,
		"width":$("input.address.map").width(),
		"text-align":"center",
		"font-size":"12pt",
		"color":"black"	,
		"border-radius":"0px 0px 10px 10px"
	});
}

function waitResponse(e){
	stopWatch();
	$("#response").css({
		"display":"block"
	});
	$("#map_canvas").css({
		"display":"block"
	});
	$("#requestAddress").css({
		"display":"block"
	});
	initialize();
	documentCss();
}


function responseFunction(){
	$("#map_canvas").css({
		"display":"none"
	});
	$("#response").css({
		"display":"none"
	});
	$("#startWaiting").css({
		"display":"inline",
		"vertical-align": "middle",
		"height":160.5 / 3,
		"width":159 / 3,
	});
	$("#waitInstruction").css({
		"display":"block"
	});
	$("#requestAddress").css({
		"display":"none"
	});
} 

function makeButton(e){
	var elementWidth = $(e).width();
	var elementHeight = $(e).height();
	$(e).on("mouseover",function(){
		$(this).css({
			"cursor":"pointer"
		});
	});
	$(e).on("mouseout",function(){
		$(this).css({
			"cursor":"default"
		});
	});
	$(e).css({
		"transition" :	"width 0.3s, height 0.3s",
		"-webkit-transition": "width 0.3s, height 0.3s",
	});
	$(e).on("mousedown",function(){
		$("#startWaiting").css({
			"height":elementWidth*9/10,
			"width":elementHeight*9/10,
		});
	});
	$(e).on("mouseup",function(){
		$("#startWaiting").css({
			"height":elementWidth,
			"width":elementHeight
		});
	});
}

var map;
var driverPosition;
var currentPosition; 
var penalty = 0;
var mapdiv = document.getElementById("map_canvas");
var marker;
var myLatlng;
var geocoder;


function driverPositionMap(location) {
	geocoder = new google.maps.Geocoder();
	driverPosition = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
  	var mapOptions = {
  		center: driverPosition,
		zoom: 17,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
	marker = new google.maps.Marker({
		position: driverPosition,
		map: map,
   		title: "Hello",
   	});
	showAddress();
	marker.setDraggable(true);
	google.maps.event.addListener(marker,'mouseup', function(){
		driverPosition=marker.getPosition();
		map.setCenter(driverPosition);
		showAddress();
	});
}

function codeAddress() {
	var address = $("input.address.map").val();
	geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
		  driverPosition = results[0].geometry.location;
		  map.setCenter(driverPosition);
		  marker.setPosition(driverPosition);
		  showAddress(driverPosition);
		} else {
		  alert("다음과 같은 이유로 실행되지 않았습니다 : " + status);
		}
	});
}

function showAddress(){
	$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?latlng="+driverPosition.lat()+","+driverPosition.lng()+'&sensor=false&language=ko', function(e){
		var addressArray = e.results[0].formatted_address.split(" ");
		var finalAddress = "";
		for(var i = 0; i < addressArray.length;i++){
			if(i!=0 && i!=1 && i!=2){
				finalAddress = finalAddress + " " + addressArray[i];  
			};
		}
		$("#requestAddress").text(finalAddress +"  에 있습니까?");
	});
}

function initialize() {
	myLatlng = new google.maps.LatLng(currentPosition.split(",")[0], currentPosition.split(",")[1]);
  	var mapOptions = {
  		center: myLatlng,
		zoom: 17,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
	};
  	map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
	marker = new google.maps.Marker({
		position: myLatlng,
		map: map,
  		title: "Hello",
   	});
  	$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng='+currentPosition+'&sensor=false&language=ko', function(e){
   		var addressArray = e.results[0].formatted_address.split(" ");
		var finalAddress = "";
		for(var i = 0; i < addressArray.length;i++){
			if(i!=0 && i!=1 && i!=2){
				finalAddress = finalAddress + " " + addressArray[i];  
			};
		}
		$("#requestAddress").text(finalAddress +"  에서 콜 했습니다.!");
	});
}

var addressDat;
var addressParam = [];
var addressUnit = ["읍","면","동","구","군","시","도"];
var addressMap = {};
var queryName = ["dong","dong","dong","gugun","gugun","sido","sido"];
var addressUnitLevel = null;
var requestLevel = null;
var siCheck = false;
var si;
var doName = ["경기","전남","전북","강원","제주","경남","경북","강원"];
var fullDoName = [null, "전라남도","전라북도",null,null,"경상남도","경상북도",null];
var siName = ["서울","울산","부산","대구","인천","광주","대전"];
var prevStringArr= [""];
var options=[""];
var currNum = 0;
var choicePosition = false;
function check(e){
	if(e.keyCode == 38 || e.keyCode == 40){
		$("div.address.option."+currNum).css({
			"background-color":"white",
		});
		currNum = (e.keyCode == 38)?currNum-1:currNum+1;
		currNum = (currNum < 0)?options.length - 1:(currNum == options.length)?0:currNum;
		$("div.address.option."+currNum).css({
			"background-color":"#E6E6E6",
		});
		if(currNum == 0){
			$("input.address.map").val(options[0]);
		}else{
			$("input.address.map").val($("div.address.option."+currNum).text().trim());	
		}
		return;
	}
	
	if(e.keyCode == 32 || e.keyCode == 8 || e.keyCode == 46){
		$("div.address.option").css({
			"background-color":"white",
		});
		currNum = 0;
		beforeAddresSearch();
	}else if(e.keyCode == 13){
		if(addressUnitLevel<3){
			emptyChoice(false);
		}
		check({keyCode:32});
		currNum = 0;
		$("input.address.map").focus();
	}
	
	options[0] = $("input.address.map").val();
}

function beforeAddresSearch(){
	var currStringArr = $("input.address.map").val().trim().split(" ");
	if(doName.indexOf(currStringArr[0]) != -1){
		currStringArr[0] = currStringArr[0]+"도";
	}else if(siName.indexOf(currStringArr[0]) != -1){
		currStringArr[0] = currStringArr[0]+"시";
	}else if(fullDoName.indexOf(currStringArr[0]) != -1){
		currStringArr[0] = doName[fullDoName.indexOf(currStringArr[0])]+"도";
	}
	deleteArr(currStringArr,prevStringArr);
	addArr(currStringArr,prevStringArr);
	addressUnitLevelControl();
	addressSearch(addressParam[addressUnitLevel]);
	prevStringArr = currStringArr;	
}

function addArr(currStringArr,prevStringArr){
	for(var i = 0; i < currStringArr.length;i++){
		if(prevStringArr.indexOf(currStringArr[i]) == -1){
			var missingWord = currStringArr[i];
			var lastChar = missingWord.substring(missingWord.length - 1,missingWord.length);
			if(addressUnit.indexOf(lastChar) != -1){
				addressParam[addressUnit.indexOf(lastChar)] = missingWord.substring(0,missingWord.length - 1);
			};
		};
	};
}

function deleteArr(currStringArr,prevStringArr){
	for(var i = 0; i < prevStringArr.length;i++){
		if(currStringArr.indexOf(prevStringArr[i]) == -1){
			var missingWord = prevStringArr[i];
			var lastChar = missingWord.substring(missingWord.length - 1,missingWord.length);
			if(addressUnit.indexOf(lastChar) != -1){
				if(!si && lastChar == "시"){
					addressParam[4] = null;						
				}else{
					addressParam[addressUnit.indexOf(lastChar)] = null;	
				};
			};
		};
	};
}

function addressSearch(input){
	if((addressUnitLevel != null && requestLevel == null) || (requestLevel < addressUnitLevel)){
		requestLevel = addressUnitLevel;
		$.getJSON("/kosta_project_final_taxi/zipcode.do", queryName[requestLevel]+"="+addressParam[requestLevel] + "&addressUnitLevel=" + addressUnitLevel,
		function(e){
			if(e != null){
				addressDat = e;
				si = (siName.indexOf(addressDat.address[0].sido) != -1)?true:false;
				showOptions();
			}
		});
	}else if((addressUnitLevel == null) && (requestLevel != null)){
		requestLevel = null;
	}
}

function addressUnitLevelControl(){
	for(var i=0;i<addressParam.length;i++){
		if(addressParam[i] != null){
			if(addressUnitLevel != i || addressUnitLevel == null){
				addressUnitLevel = i;
				if(addressUnitLevel <= requestLevel){
					showOptions();
				};
			}
			return;
		};
	};
	addressUnitLevel = null;
	emptyChoice(false);
}

function showOptions(){
	options=[options[0]];
	var repeat = ["check"];
	var tempAddressParam = addressParam;
	if(!si && addressUnitLevel == 5){
		addressUnitLevel = 4;
		requestLevel = 4;
	};
	if(!si && tempAddressParam[5] != null){
		tempAddressParam[4] = tempAddressParam[5]+"시"; 
		tempAddressParam[5] = null;
	};
	emptyChoice(true);
	for(var i=0 ; i < addressDat.address.length; i++){
		var check2 = true;
		if(addressUnitLevel < 3){
			var checkDongArr = addressDat.address[i][queryName[addressUnitLevel]].split(" ");
			if(checkDongArr[0] != tempAddressParam[addressUnitLevel]+addressUnit[addressUnitLevel]){
				check2 = false;	
			};
		};
		if(check2){
			for(var l=addressUnitLevel;l<7;l=l+1){
				if(tempAddressParam[l] != null){
					var check3 = addressDat.address[i][queryName[l]];
					if(check3.indexOf(tempAddressParam[l]) == -1){
						check2 = false;
						break;
					}
				};
			};
		};
		if(check2){
			var check = addressDat.address[i][queryName[addressUnitLevel]];
			var nextAddressUnitLevel = (addressUnitLevel<3)?addressUnitLevel:(check.indexOf(" ") != -1)?addressUnitLevel-1:addressUnitLevel-2;
			var repeatInput = addressCheck(addressDat.address[i][queryName[nextAddressUnitLevel]],nextAddressUnitLevel, i);
			if(repeat.indexOf(repeatInput) == -1){
				var finalAddress = "";
				repeat.push(repeatInput);
				for(var k=nextAddressUnitLevel;k<7;k=k+2){
					finalAddress = addressCheck(addressDat.address[i][queryName[k]], k, i) + " " + finalAddress;
					if(k==0){
						k=k+1;
					};
				};
				options.push(finalAddress);
				$("div.address.choice").append("<div class=\"address option " + (options.length-1) + "\">"+finalAddress +"</div>");
				$("div.address.option." + (options.length-1)).css({
					"font-family":"myFont",
					"margin":"10px 0",
				});
			};
		};
	};
};

function addressCheck(p, j, i){
	if(addressUnitLevel < 3){
		if(j < 3 && addressDat.address[i].bunji != null){
			p = p + " " + addressDat.address[i].bunji;
		}
		return p;
	}else{
		if(p.indexOf(" ") != -1){
			var pArr = p.split(" ");
			p = "";
			if(j<3 || (addressUnitLevel == 6)){
				p = pArr[0];
			}else{
				for(var i=0;i<pArr.length;i++){
					p = p + " " + pArr[i];
					var lastChar = pArr[i].charAt(pArr.length-1);
					if(lastChar == addressUnit[j]){
						break;
					};
				};
			};
		};
		return p;
	};
}

function emptyChoice(show){
	$("div.address.choice").empty();
	if(show){
		$("div.address.choice").css({
			"display":"block"
		});	
	}else{
		$("div.address.choice").css({
			"display":"none"
		});
	}
};

function updateWatch(){
	var sec = parseInt($('#wait_time').find('.watch.second').text(), 10);
	var min = parseInt($('#wait_time').find('.watch.minute').text(), 10);
	var hour = parseInt($('#wait_time').find('.watch.hour').text(), 10);;
	sec++;
	if (sec == 60) {
		sec = 0;
		min = min + 1;
	}
	if (min == 60) {
		min = 0;
		hour += 1; 
	}
	if(sec < 10){
		sec = "0"+sec;
	}
	if(min < 10){
		min = "0"+min;
	}
	if(hour < 10){
		hour = "0"+hour;
	}
	$('#wait_time').find('.watch.second').text(sec);
	$('#wait_time').find('.watch.minute').text(min);
	$('#wait_time').find('.watch.hour').text(hour);
}

var watchInterval;
function startWatch() {
	watchInterval = setInterval(updateWatch, 1000);
	$("#submit").css({
		"display":"none"
	});
	$("#wait_time").css({
		"display":"block",
		"margin-top":"20px",
		"magin-right":"auto",
		"margin-left":"auto"
	});
	$("span.watch").css({
		"margin":"0 10px 0 10px",
		"text-align":"right"
	});
}

function stopWatch(){
	$('#wait_time').find('.watch.second').text("00");
	$('#wait_time').find('.watch.minute').text("00");
	$('#wait_time').find('.watch.hour').text("00");
	clearInterval(watchInterval);
	$("#wait_time").css({
		"display":"none",
	});
};
</script>
<div class="main">
	<div class="address">
		<div>
			<input type="text" class="address map">
			<input class="address move" type="button" value="이동" onclick="codeAddress()">
		</div>
		<div class="address choice">
		</div>
	</div>
	<div id="map_canvas"></div>
	<div id="requestAddress"></div>
	<div id="wait_time">
		대기시간 : <span class="watch hour">00</span>시간<span class="watch minute">00</span>분<span class="watch second">00</span>초
	</div> 
	<div id="waitInstruction">대기 시작 <img id="startWaiting" src="/kosta_project_final_taxi/img/wait.png" alt="대기 시작"/></div>
	<div id="response">
	<div id="accept">수락</div> <div id="reject">거절</div>
	</div>
</div>